<script lang="ts" setup>
import { computed, reactive, watch } from 'vue'
import { hasOwnProp } from '../../../common/utils/normalUtils'

const emit = defineEmits(['update:modelValue', 'change', 'click'])
 const props = defineProps({
   options: {
     type: Array,
     default: function() {
       return []
     }
   },
   write: {
     type: Boolean,
     default: false
   },
   labelField: {
     type: String,
     default: 'label'
   },
   valueField: {
     type: String,
     default: 'value'
   },
   multiple: {
     type: Boolean,
     default: false
   },
   modelValue: {
     type: [Array, String, Number],
     default: ''
   },
   multipleString: {
     type: Boolean,
     default: true
   },
   dotBound: {
     type: Boolean,
     default: false
   },
   placeholder: {
     type: String,
     default: ''
   },
   defaultSelect: {
     type: Boolean,
     default: false
   }
 })

const state = reactive({
  inputValue: props.modelValue
})


const changeHandler = (val:any) => {
  const value = getModelValue(val)
  emit('update:modelValue', value)
  emit('change', value)
}

/**
 *
 * @param val
 */
const getModelValue = (val:any) => {
  const value = val
  return value
}

const getItem = (val:any) => {
  // emit('update:modelValue', val)
  emit('click', val)
}

watch(() => props.modelValue, (val:any) => {
  state.inputValue = val
  if (props.dotBound && getModelValue(state.inputValue) !== val) { changeHandler(state.inputValue) }
})

const labelRender = (item:any) => {
  const lbF = props.labelField as any
  return (item && hasOwnProp(item, lbF) && item[lbF]) ? item[lbF] : ''
}
const valueRender = (item:any) => {
  const lbF = props.valueField as any
  return (item && hasOwnProp(item, lbF) && item[lbF] !== undefined && item[lbF] !== null) ? item[lbF] : ''
}

</script>

<template>
  <el-select v-model="state.inputValue"
             :multiple="multiple"
             :placeholder="placeholder"
             @change="changeHandler">
    <slot>
      <el-option v-for="item of options"
                 :key="valueRender(item)"
                 :label="labelRender(item)"
                 :value="valueRender(item)"
                 :disabled="item.disabled"
                 @click.native="getItem(item)" />
    </slot>
    <template #empty>
      <slot name="empty">
        <div class="empty-text">
          暂无数据
        </div>
      </slot>
    </template>
  </el-select>
</template>

<style scoped lang="scss">
  .empty-text{
    flex:none;
    width:100%;
    line-height:32px;
    vertical-align: middle;
    color:var(--w-color-nor2);
    text-align: center;
  }
</style>
